package com.zy.ivideo.service;

import com.zy.ivideo.entity.CommentEntity;
import com.zy.ivideo.entity.ReplyEntity;
import com.zy.ivideo.entity.ResponseEntity;
import com.zy.ivideo.repository.CommentRepository;
import com.zy.ivideo.repository.ReplyRepository;
import com.zy.ivideo.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {
    @Autowired
    CommentRepository commentRepository;
    @Autowired
    ReplyRepository replyRepository;

    /**
     * 发布评论
     * @param entity
     * @return
     */
    public ResponseEntity<CommentEntity> publishComment(CommentEntity entity){
        CommentEntity result = commentRepository.save(entity);
        if (result!=null){
            return ResponseUtils.success(result);
        }
        return ResponseUtils.failed("评论发布失败");
    }

    /**
     * 删除评论
     * @param id
     * @return
     */
    public ResponseEntity<Boolean> removeComment(Long id){
        try{
            commentRepository.deleteById(id);
            //删除评论对应的回复信息
            replyRepository.removeByCommentId(id);
            return ResponseUtils.success(true);
        }catch (Exception ex){
            return ResponseUtils.failed("删除评论失败");
        }
    }

    /**
     * 获取评论信息
     * @param datatype
     * @param itemid
     * @return
     */
    public ResponseEntity<List<CommentEntity>> getCommentById(int datatype,String itemid){
        List<CommentEntity> result = commentRepository.getCommentById(datatype, itemid);
        if (result!=null&&result.size()>0){
            for (CommentEntity entity:result){
                List<ReplyEntity> replyList = replyRepository.getReplyByCommentId(entity.getId());
                entity.setReplyList(replyList);
            }
            return ResponseUtils.success(result);
        }
        return ResponseUtils.failed("没有获取到评论信息");
    }

    /**
     * 点赞
     * @param commentid
     * @return
     */
    public ResponseEntity<Boolean> agree(int commentid){
        int result = commentRepository.modifyAgreeNum(commentid, 1);
        if (result>0){
            return ResponseUtils.success(true);
        }
        return ResponseUtils.failed("点赞失败");
    }

    /**
     * 取消点赞
     * @param commentid
     * @return
     */
    public ResponseEntity<Boolean> unAgree(int commentid){
        int result = commentRepository.modifyAgreeNum(commentid, -1);
        if (result>0){
            return ResponseUtils.success(true);
        }
        return ResponseUtils.failed("取消点赞失败");
    }

}
